# -*- coding: utf-8 -*-
#
#    pyqtsozluk, qtsozluk and pysozluk mix dictionary application
#    Copyright (C) 2007  pyqtsozluk authors
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#

from PyQt4 import QtCore
from gettext import translation
from database import pysozlukDatabase
from online import onlineDatabase

_ = translation('pyqtsozluk', fallback=True).ugettext

class searcherThread(QtCore.QThread):
    def __init__(self, keyword, offline, smart):
        QtCore.QThread.__init__(self)
        self.keyword = keyword
        self.offline = offline
        self.smart = smart

    def run(self):
        if self.offline:
            self.database = pysozlukDatabase()
        else:
            self.database = onlineDatabase()
        QtCore.QObject.connect(self.database, QtCore.SIGNAL("found"), self.formatTranslation)
        self.database.search(self.keyword)
        self.exec_()

    def formatTranslation(self, translation):
        turkish = []
        english = []
        tr = "<img src='/usr/share/pyqtsozluk/images/tr.gif'><br><b>" + _("Turkish translation of %s") % self.keyword + "</b><br>"
        en = "<img src='/usr/share/pyqtsozluk/images/en.gif'><br><b>" + _("English translation of %s") % self.keyword + "</b><br>"
        result = ""

        if translation:
            for var in translation:
                if var.lang == 1 and not var.text in english:
                        english.append(var.text)
                elif var.lang == 0 and not var.text in turkish:
                        turkish.append(var.text)
            if turkish:
                for text in turkish:
                    tr += "%d. %s<br>" % (turkish.index(text)+1, text)
                tr += "<br>"
                result += tr

            if english:
                for text in english:
                    en += "%d. %s<br>" % (english.index(text)+1, text)
                result += en
            self.sendHtml(result.replace('"',''))
        else:
            if self.offline and self.smart:
                self.offline = False
                self.database = onlineDatabase()
                QtCore.QObject.connect(
                    self.database,
                    QtCore.SIGNAL("found"),
                    self.formatTranslation)
                self.database.search(self.keyword)
                self.sendHtml("<b>" + _("Cannot find \"%s\"") % self.keyword +\
                              "<br/>" + _("Now searching online...") + "</b>")
            else:
                self.sendHtml("<b>" + _("Cannot find \"%s\"") % self.keyword + "</b>")

    def sendHtml(self, result):
        self.emit(QtCore.SIGNAL("finishedSearching"), result)


class pysozlukCore:
    def __init__(self, ui):
        self.ui = ui
        self.settings = QtCore.QSettings()
        self.ui.actionOffline.setChecked(self.settings.value("search/offline", QtCore.QVariant(True)).toBool())
        self.searcherThread = None
        self.settingsUi = None

    def search(self): # OK
        #TODO: This should display country flags
        keyword = unicode(self.ui.lineEdit.text())
        if self.searcherThread and self.searcherThread.isRunning():
            self.searcherThread.terminate()
        self.searcherThread = searcherThread(
            keyword,
            self.settings.value("search/offline",
            QtCore.QVariant(True)).toBool(),
            self.settings.value("search/smartSearch",
            QtCore.QVariant(True)).toBool())
        self.ui.textBrowser.clearHistory()
        self.ui.textBrowser.setHtml("<b>%s</b>" % _("searching \"%s\"")%keyword)
        QtCore.QObject.connect(self.searcherThread,
                               QtCore.SIGNAL("finishedSearching"),
                               self.ui.textBrowser.setHtml)
        self.searcherThread.start()


